package com.example.harmtorch_demo.slice;

import com.example.harmtorch_demo.harmtorch.Tensor;
import ohos.global.resource.Resource;

import java.io.FileNotFoundException;
import java.io.IOException;

// used for transform image data to tensor
public class DataReader {
    byte[] buffer;

    final int imageWid = 28;
    final int imageHei = 28;

    Resource resource;

    public DataReader(Resource resource){
        this.resource = resource;
    }


    public Tensor read() throws Exception{
        buffer = new byte[imageHei * imageWid];
        if(resource.read(buffer, 0, 16) < 16){
            throw new FileNotFoundException("File size < 16B.");
        }

        byte[] bnum = new byte[]{buffer[4], buffer[5], buffer[6], buffer[7]};
        String snum = byteToArray(bnum);
        int photonum = Integer.parseInt(snum, 16);
        System.out.printf("The number of photos: %d%n", photonum);


        Tensor image = new Tensor(1, imageWid * imageHei);

        if (resource.read(buffer) != -1) {    // viable bit
            image.setTensorWithNormalization(buffer);
        }
        else {
            throw new Exception("File size is smaller than expected.");
        }

        return image;

    }

    public int readMul(Tensor[] tensorArray, int num) throws Exception{
        buffer = new byte[imageHei * imageWid];
        if (resource.read(buffer, 0, 16) < 16){
            throw new FileNotFoundException("File size < 16B.");
        }

        byte[] bnum = new byte[]{buffer[4], buffer[5], buffer[6], buffer[7]};
        String snum = byteToArray(bnum);
        int photonum = Integer.parseInt(snum, 16);
        System.out.printf("The number of photos: %d%n", photonum);

        int i;
        for(i = 0; i < num; i++){
            if(resource.read(buffer) != -1){    // viable bit
                Tensor image = new Tensor(1, imageWid * imageHei);
                image.setTensorWithNormalization(buffer);
                tensorArray[i] = image;
            }
            else{
                // throw new Exception("File size is smaller than expected.");
                break;
            }
        }
        return i;
    }

    static String byteToArray(byte[] data){
        String result = "";
        for (int i = 0; i < data.length; i++) {
            result += Integer.toHexString((data[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3);
        }
        return result;
    }
}
